package com.pocketsweet.ui.fragments;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.R;
import com.pocketsweet.dao.SystemConfigManager;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.TempMain;
import com.pocketsweet.ui.uilib.MyBitmapFactory;

public class WelcomeFour extends Fragment {
	@ViewInject(R.id.welcome4)
	private ImageView welcome4;
	
	@ViewInject(R.id.tvStart)
	private TextView tvStart;

	@ViewInject(R.id.tvGirlHeadVoice)
	private TextView tvGirlHeadVoice;

	@ViewInject(R.id.tvBoyHeadVoice)
	private TextView tvBoyHeadVoice;

	@ViewInject(R.id.girlVoiceProgressBar)
	private ProgressBar girlVoiceProgressBar;

	@ViewInject(R.id.boyVoiceProgressBar)
	private ProgressBar boyVoiceProgressBar;
	
	MyThread girlThread;
	MyThread boyThread;
	SoundPool sp;
	HashMap<Integer, Integer> spMap;
	private int mPresentPlayId;
	private static int VOICE_STOP_GIRL = 3;
	private static int VOICE_STOP_BOY = 4;
	private static int GIRL_VOICE = 1;
	private static int BOY_VOICE = 2;
	private static int GIRL_VOICE_TIME = 190; // 女声时间,秒数＊10
	private static int BOY_VOICE_TIME = 180; // 男声时间
	final Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == GIRL_VOICE) {
				// 设置进度条当前的完成进度
				girlVoiceProgressBar.setProgress(girlThread.getProgress());
			} else if (msg.what == BOY_VOICE) {
				boyVoiceProgressBar.setProgress(boyThread.getProgress());
			} else if (msg.what == VOICE_STOP_GIRL) {
				girlVoiceProgressBar.setProgress(0);
			} else if (msg.what == VOICE_STOP_BOY) {
				boyVoiceProgressBar.setProgress(0);
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_welcome_4, null);
		ViewUtils.inject(this, rootView);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		InitSound();
//		welcome4.setImageBitmap(MyBitmapFactory
//				.decodeSampledBitmapFromResource(getResources(),
//						R.drawable.welcome4, 260, 596));
//		Picasso.with(getActivity()).load(R.drawable.welcome4).into(welcome4);  
		UserService.displaySplashImage(R.drawable.welcome4, welcome4);

//		welcome4.setImageDrawable(getResources().getDrawable(R.drawable.welcome4));
	}

	public void InitSound() {
		sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
		spMap = new HashMap<Integer, Integer>();
		spMap.put(1, sp.load(getActivity(), R.raw.voice_gril, 1));
		spMap.put(2, sp.load(getActivity(), R.raw.voice_boy, 1));
		girlVoiceProgressBar.setMax(GIRL_VOICE_TIME);
		boyVoiceProgressBar.setMax(BOY_VOICE_TIME);
	}

	public void playSound(int sound, int number) {
		AudioManager am = (AudioManager) getActivity().getSystemService(
				Context.AUDIO_SERVICE);
		float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float volumnCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		float volumnRatio = volumnCurrent / audioMaxVolumn;

		mPresentPlayId = sp.play(spMap.get(sound), volumnRatio, volumnRatio, 1,
				number, 1f);

	}

	@OnClick(R.id.tvStart)
	public void onStartClick(View v) {
		Intent intent = new Intent(getActivity(), TempMain.class); // 从启动动画ui跳转到主ui
		startActivity(intent);
		getActivity().finish();
		SystemConfigManager.getInstance(getActivity()).setFirstRun(false);
	}

	@OnClick(R.id.tvGirlHeadVoice)
	public void onClicktvGirlHeadVoice(View v) {
		sp.stop(spMap.get(1));
		playSound(2, 0);
		if (girlThread != null) {
			girlThread.isStop = true;
		}
		if (boyThread != null) {
			boyThread.isStop = true;
		}
		girlThread = new MyThread(GIRL_VOICE);
		girlThread.start();

	}

	@OnClick(R.id.tvBoyHeadVoice)
	public void onClicktvBoyHeadVoice(View v) {
		sp.stop(spMap.get(2));
		playSound(1, 0);

		if (girlThread != null) {
			girlThread.isStop = true;
		}
		if (boyThread != null) {
			boyThread.isStop = true;
		}
		boyThread = new MyThread(BOY_VOICE);
		boyThread.start();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mPresentPlayId != 0) {
			sp.pause(mPresentPlayId);
		}
		if (girlThread != null) {
			girlThread.pauseThread();
			girlThread.onPause();
		}
		if (boyThread != null) {
			boyThread.pauseThread();
			boyThread.onPause();
		}

	}

	@Override
	public void onResume() {
		super.onResume();
		if (mPresentPlayId != 0) {
			sp.resume(mPresentPlayId);
		}
		if (girlThread != null) {
			girlThread.onResume();
		}
		if (boyThread != null) {
			boyThread.onResume();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mPresentPlayId != 0) {
			sp.stop(mPresentPlayId);
		}
		releaseImageViews();
	}

	class MyThread extends Thread {
		private Object mPauseLock;
		private boolean mPauseFlag;
		private int count;
		private int stop;
		private int progress;
		private int girlOrBoy;
		private boolean isStop;

		public MyThread() {

			mPauseLock = new Object();
			mPauseFlag = false;
		}

		public MyThread(int girlOrBoy) {
			this.girlOrBoy = girlOrBoy;
			mPauseLock = new Object();
			mPauseFlag = false;
			if (girlOrBoy == GIRL_VOICE) {
				this.count = GIRL_VOICE_TIME;
				this.stop = VOICE_STOP_GIRL;
			} else {
				this.count = BOY_VOICE_TIME;
				this.stop = VOICE_STOP_BOY;

			}
		}

		public int getProgress() {
			return progress;
		}

		public void setProgress(int progress) {
			this.progress = progress;
		}

		public boolean isStop() {
			return isStop;
		}

		public void setStop(boolean isStop) {
			this.isStop = isStop;
		}

		public void onPause() {
			synchronized (mPauseLock) {
				mPauseFlag = true;
			}
		}

		public void onResume() {
			synchronized (mPauseLock) {
				mPauseFlag = false;
				mPauseLock.notifyAll();
			}
		}

		private void pauseThread() {
			synchronized (mPauseLock) {
				if (mPauseFlag) {
					try {
						mPauseLock.wait();
					} catch (Exception e) {
//						Log.v("thread", "fails");
					}
				}
			}
		}

		@Override
		public void run() {
			isStop = false;
			for (int i = 0; i < count; i++) {
				try {
					if (isStop) {
						Message msg = new Message();
						msg.what = stop;
						mHandler.sendMessage(msg);
						break;
					}
					if (mPauseFlag) {
						this.pauseThread();
						// this.wait();
					}
					// if (isWake) {
					// boyThread.notify();
					// isWake = false;
					// isSleep =false;
					// }
					// 设置计数器
					progress = i;
					// 设置线程的休眠时间
					if (i != 0)
						Thread.sleep(100);
					// 进度条是100%的时候发送STOP信息给mHandler
					if (i == count - 1) {
						// Message msg = new Message();
						// msg.what = VOICE_STOP_GIRL;
						// mHandler.sendMessage(msg);
						// 当值不为19时，也就是进度条还没有达到百分百时候，发送NEXT信息给mHandler
					} else {
						Message msg = new Message();
						msg.what = girlOrBoy;
						mHandler.sendMessage(msg);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	}


	private void releaseImageViews() {
		MyBitmapFactory.releaseImageViewResouce(welcome4);
	}
}
